<template>
	<view class="container">
		<view class="line"></view>
		<view class="list-null" v-if="isScan">
			<view class="null-text">正在搜索附近的设备,确保设备处于配网状态</view>
			<image class="null-icon" :src="$IMAGE_BASE_URL + '/static/ic_blue_search.gif'"></image>
		</view>
		<view class="title" v-if="!isScan">已找到以下设备</view>
		<view class="tip" v-if="isShowBleTip">提示：请检查是否已经打开手机定位和手机蓝牙</view>
		<!-- <scroll-view scroll-y class="list-scroll" v-if="!isScan"> -->
		<scroll-view scroll-y class="list-scroll">
			<view class="list">
				<view class="list-item" v-for="(item, index) in deviceList" :key="index" @click="onDevice(item)">
					<!-- <image class="img" src="@/static/ic_light.png" mode="heightFix"></image> -->
					<image class="img" :src="item.product.pic" mode="heightFix"></image>
					<view class="info">
						<view class="name">{{ item.wifiMac || item.deviceId }}</view>
						<image v-if="item.selected" class="btn" :src="$IMAGE_BASE_URL + '/static/ic_selected.png'">
						</image>
						<image v-else class="btn" :src="$IMAGE_BASE_URL + '/static/ic_unselected.png'"></image>
					</view>
				</view>
			</view>
		</scroll-view>
		<BaseButton shape="circle" text="添加" :disabled="isBtnDisable" @click="onAdd" />
	</view>
</template>

<script>
	import BaseButton from "@/components/base-button/index.vue";
	import ProductScanService from "@/service/ProductScanService";
	import MessageConfig from "@/config/MessageConfig.js";
	import EventUtils from "@/utils/EventUtils.js";
	import BluDeviceComService from "@/service/BluDeviceComService.js";
	import DeviceConfig from "@/config/DeviceConfig";
	import * as DeviceApi from "@/api/device/index.js";
	import {
		showLoading,
		hideLoading,
		showInfo,
	} from "@/utils/ToastUtils.js";

	export default {
		data() {
			return {
				isBlue: false,
				isScan: false,
				deviceList: [],
				device: {},
				isJump: true,
				isConnect: false,
			};
		},
		components: {
			BaseButton
		},
		computed: {
			isShowBleTip() {
				return (!this.$addDeviceService.isSubDevice) || (this.$addDeviceService.isSubDevice && this.$addDeviceService.isLight);
			},
			isBtnDisable() {
				const selectedList = this.deviceList.filter(v => v.selected);
				return selectedList.length <= 0;
			}
		},
		onShow() {
			this.init();
		},
		onHide() {
			EventUtils.off(MessageConfig.BlE_CONNECT_TYPE);
		},
		methods: {
			init() {
				this.isJump = true;
				if (this.$addDeviceService.isSubDevice) {
					if (this.$addDeviceService.isLight) {
						this.blueScan([DeviceConfig.DEVICE_NAME]);
					} else {
						this.mqttScan();
					}
				} else {
					this.blueScan([DeviceConfig.DEVICE_NAME]);
				}
			},
			blueScan(blueNames) {
				EventUtils.on(MessageConfig.BlE_CONNECT_TYPE, this.listenBlueConnect);
				this.ProductScanService = new ProductScanService();
				this.ProductScanService.scanDevice([...blueNames], {
					start: (isBlue) => {
						console.log("开始扫描=====================");
						console.log("蓝牙适配器是否可用", isBlue);
						this.isScan = true;
						this.isBlue = isBlue;
					},
					end: () => {
						console.log("结束扫描=====================");
						this.isScan = false;
					},
					found: (devices) => {
						console.log("found devices", devices);
						// 过滤设备
						// this.deviceList = devices.filter(v => v.wifiMac == "B8:3D:FB:E0:62:F5");
						this.deviceList = devices.filter(v => v.wifiMac == this.$addDeviceService.device.deviceName);
						// 不过滤
						// this.deviceList = devices;
						this.deviceList = JSON.parse(JSON.stringify(this.deviceList));
						this.deviceList = this.removeDuplicates(this.deviceList);
					}
				})
			},
			async mqttScan() {
				try {
					console.log("mqtt推送台灯扫描到的蓝牙设备");
					const deviceDataRes = await DeviceApi.getPropert({
						deviceId: this.$addDeviceService.device.deviceId
					});
					console.log("deviceDataRes", deviceDataRes);
					const deviceData = deviceDataRes.obj;
					const childDevices = deviceData["childDevices"];
					console.log("childDevices", childDevices);
					let deviceList = [];
					if(!!childDevices) {
						deviceList = JSON.parse(childDevices.value) || [];
					}
					const index = deviceList.findIndex(v => v.mac == this.$addDeviceService.subDevice.deviceName);
					console.log("index", index);
					if(index == -1) {
						deviceList.push({
							pk: this.$addDeviceService.subDevice.productKey,
							mac: this.$addDeviceService.subDevice.deviceName,
							sta: 0
						})
					}
					// [{pk:"U66HAhigSMV",mac:"C0:00:00:0A:54:F5",sta:0}]
					// [{pk:"U66HAhigSMV",mac:"C0:00:00:0A:54:F5",sta:0},{pk:"R91EknwemOo",mac:"00:A0:50:2E:59:91",sta:0},{pk:"u74nczhPSsR",mac:"81:2A:2A:01:1B:88",sta:0}]
					console.log("添加的子设备 json", deviceList);
					// const setParam = {
					// 	deviceName: this.$addDeviceService.device.deviceName,
					// 	productKey: this.$addDeviceService.device.productKey,
					// 	identifier: "childDevices",
					// 	value: deviceList,
					// 	type: "string",
					// };
					// console.log("setParam", setParam);
					// const setRes = await DeviceApi.getdeviceSet(setParam);
					// console.log("setRes", setRes);
					
					this.deviceList = [{
						deviceId: this.$addDeviceService.subDevice.deviceName,
						product: {
							pic: this.$addDeviceService.subDevice.devicePic
						},
						selected: true,
					}];
				} catch(err) {
					console.log("mqttScan error", err);
					showInfo("连接失败：星梦云康请重新配置网络");
				}
			},
			listenBlueConnect(res) {
				console.log("连接监听", res);
				const {
					deviceId,
					connected
				} = res;
				if (this.device.deviceId == deviceId) {
					if (connected) {
						console.log("连接上的设备", this.device);
						const {
							deviceId,
							product,
							name
						} = this.device;
						// const {
						// 	productKey
						// } = product
						hideLoading();
						if (this.isJump) {
							this.isJump = false;
							console.log("连接成功 跳转到网络配置页面");
							uni.navigateTo({
								url: `/pages/addDevice/configWifi?blueMac=${deviceId}&productKey=${product.productKey}`
							})
						}
					} else {
						if (this.isConnect) {
							hideLoading();
							showInfo("连接失败");
							this.isConnect = false;
						}
					}
				}
			},
			onDevice(item) {
				if(this.ProductScanService) {
					this.ProductScanService.stop();
				}
				const index = this.deviceList.findIndex(v => v.deviceId == item.deviceId);
				console.log("deviceList", index);
				if (index < 0) return;
				for (let i = 0; i < this.deviceList.length; i++) {
					if(index == i) {
						this.deviceList[i].selected = !this.deviceList[i].selected;
					}else {
						this.deviceList[i].selected = false;
					}
				}
			},
			onAdd() {
				if (this.$addDeviceService.isSubDevice) {
					if (this.$addDeviceService.isLight) {
						this.linkDevice();
					} else {
						this.linkSubDevice();
					}
				} else {
					this.linkDevice();
				}
			},
			async linkDevice() {
				console.log("连接设备");
				this.ProductScanService.stop();
				showLoading();
				this.isConnect = false;
				const deviceList = this.deviceList.filter(v => v.selected);
				this.device = deviceList[0];
				console.log("device", this.device);
				await BluDeviceComService.disconnetBlue(this.device.deviceId);
				this.isConnect = true;
				await BluDeviceComService.connetBlue(this.device.deviceId);
			},
			async linkSubDevice() {
				try {
					console.log("添加从设备");
					const param = {
						deviceName: this.$addDeviceService.subDevice.deviceName,
						deviceType: this.$addDeviceService.subDevice.deviceType,
						uuid: this.$addDeviceService.uuid,
					};
					console.log("bindDevice param", param);
					await DeviceApi.bindDevice(param);
					// showInfo("绑定成功");
					// this.$addDeviceService.clear();
					// uni.switchTab({
					// 	url:'/pages/index/index'
					// })
					uni.navigateTo({
						url:'/pages/addDevice/bindDeviceSuccess'
					})
				} catch(err) {
					console.log("linkSubDevice error", err);
					if (err.errMsg == 'Device is offline') {
						showInfo("添加失败：星梦云康离线");
					} else if(err.errMsg == '超时') {
						showInfo("添加失败：发送指令超时");
					}
				}
			},
			removeDuplicates(data) {
				const uniqueIds = new Set();
				return data.filter(item => {
					if (!uniqueIds.has(item.deviceId)) {
						uniqueIds.add(item.deviceId);
						return true;
					}
					return false;
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		background-color: #FFFFFF;

		.line {
			height: 20rpx;
			background-color: #F5F5F6;
		}

		.list-null {
			display: flex;
			align-items: center;
			margin: 20rpx;

			.null-text {
				font-size: 30rpx;
				color: #010101;
			}

			.null-icon {
				width: 40rpx;
				height: 40rpx;
				margin-left: 10rpx;
				margin-top: 5rpx;
			}
		}

		.title {
			font-size: 30rpx;
			font-weight: 400;
			color: #010101;
			padding: 20rpx 30rpx;
		}
		
		.tip {
			padding: 0 20rpx 10rpx 20rpx;
			font-size: 26rpx;
			font-weight: 400;
			color: #FF0000;
		}

		.list-scroll {
			height: calc(100vh - 20rpx - 330rpx);
			margin-bottom: 50rpx;

			.list {
				display: grid;
				grid-template-columns: repeat(2, 49%);
				gap: 20rpx;
				padding: 0 20rpx;

				.list-item {
					flex: 1;
					display: flex;
					flex-direction: column;
					// border: 1rpx solid #BBBBBB;
					padding: 20rpx;
					box-sizing: border-box;

					.img {
						height: 154rpx;
					}

					.info {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-top: 40rpx;

						.name {
							width: 260rpx;
							font-family: SourceHanSansCN;
							font-size: 30rpx;
							font-weight: 400;
							color: #010101;
						}

						.btn {
							width: 35rpx;
							height: 35rpx;
							// margin-right: 20rpx;
						}
					}
				}
			}
		}

	}
</style>